package cn.itsource.langxun.service.impl;

import cn.itsource.langxun.domain.Product;
import cn.itsource.langxun.domain.ProductExt;
import cn.itsource.langxun.domain.Sku;
import cn.itsource.langxun.domain.Specification;
import cn.itsource.langxun.mapper.ProductExtMapper;
import cn.itsource.langxun.mapper.ProductMapper;
import cn.itsource.langxun.mapper.SkuMapper;
import cn.itsource.langxun.mapper.SpecificationMapper;
import cn.itsource.langxun.query.ProductQuery;
import cn.itsource.langxun.service.IProductService;
import cn.itsource.langxun.util.PageList;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author lishijie
 * @since 2019-08-21
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductExtMapper productExtMapper;
    @Autowired
    private SpecificationMapper specificationMapper;
    @Autowired
    private SkuMapper skuMapper;

    /**
     * 修改商品的SKU属性
     * @param productId
     * @param skuProperties
     * @param skus
     */
    @Override
    @Transactional
    public void updateSkuProperties(long productId, List<Specification> skuProperties, List<Map<String, Object>> skus) {

        //改几张表？？？
        //修改商品扩展表的skuProperties列
        String skuPropertiesStr = JSON.toJSONString(skuProperties);
        productExtMapper.updateSkuProperties(productId,skuPropertiesStr);
        //根据productId删除sku表的数据
        skuMapper.delete(new QueryWrapper<Sku>().eq("product_id", productId));
        //向sku表中添加数据
        //将List<Map<String, Object>>转成 List<Sku>
        List<Sku> skuList = mapListToSkuList(skus,productId);
        skuList.forEach(sku->{
            skuMapper.insert(sku);
        });
    }

    private List<Sku> mapListToSkuList(List<Map<String, Object>> skus,Long productId) {
        List<Sku> skuList = new ArrayList<>();
        for (Map<String, Object> skuMap : skus) {
            Sku sku = map2Sku(skuMap,productId);
            skuList.add(sku);
        }
        return skuList;
    }

    private Sku map2Sku(Map<String, Object> skuMap,Long productId) {
        Sku sku = new Sku();
        sku.setProductId(productId);
        sku.setCreateTime(new Date().getTime());
        //skuName
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : skuMap.entrySet()) {
            if("price".equals(entry.getKey())||"store".equals(entry.getKey())){
                continue;
            }
            sb.append(entry.getValue());
        }
        sku.setSkuName(sb.toString());
        sku.setPrice(Integer.parseInt((String)skuMap.get("price")));
        sku.setAvailableStock(Integer.parseInt((String) skuMap.get("store")));
        return sku;
    }

    /**
     * 查询商品的Sku属性
     * @param productId
     * @return
     */
    @Override
    public List<Specification> getSkuProperties(Long productId) {
        ProductExt productExt = productExtMapper.selectOne(new QueryWrapper<ProductExt>().eq("product_id", productId));
        String skuProperties = productExt.getSkuProperties();
        if(StringUtils.isNotEmpty(skuProperties)){
            //[{id:1,specName:"年龄",options:["萝莉","御姐"]},{....}]
            List<Specification> specifications = JSON.parseArray(skuProperties, Specification.class);
            return specifications;
        }
        //查询属性表
        Long productTypeId = baseMapper.selectById(productId).getProductTypeId();
        List<Specification> specificationList = specificationMapper.selectList(new QueryWrapper<Specification>()
                .eq("product_type_id", productTypeId)
                .eq("isSku", 1));
        return specificationList;
    }



    /**
     * 修改显示属性
     * @param productId
     * @param viewProperties
     */
    @Override
    @Transactional
    public void updateViewProperties(Long productId, List<Specification> viewProperties) {
        String viewPropertiesStr = JSON.toJSONString(viewProperties);
        productExtMapper.updateViewProperties(productId,viewPropertiesStr);
    }


    /**
     * 查询商品的显示属性
     * @param productId
     * @return
     */
    @Override
    public List<Specification> getViewProperties(Long productId) {
        //先查询之前有没有设置过 -- 商品扩展表
        ProductExt productExt = productExtMapper.selectOne(new QueryWrapper<ProductExt>().eq("product_id", productId));
        String viewProperties = productExt.getViewProperties();
        if(StringUtils.isNotEmpty(viewProperties)){
            //不为空
            //[{id:1,name:"材质",value:"金属"},{id:2,name:"容量",value:"10L"}]
            List<Specification> specifications = JSON.parseArray(viewProperties, Specification.class);
            return specifications;
        }
        //再查询属性表
        Long productTypeId = baseMapper.selectById(productId).getProductTypeId();
        List<Specification> specificationList = specificationMapper.selectList(new QueryWrapper<Specification>()
                .eq("product_type_id", productTypeId)
                .eq("isSku", 0));
        //[{id:1,name:"材质",value:null},{id:2,name:"容量",value:null}]
        return specificationList;
    }


    /**
     * 高级分页查询
     * @param query
     * @return
     */
    @Override
    public PageList<Product> queryPage(ProductQuery query) {
        IPage<Product> iPage = baseMapper.selectPage(new Page<>(query.getPage(), query.getRows()),
                new QueryWrapper<Product>().like("tp.name", query.getKeyword()).or().like("tp.subName", query.getKeyword()));
        return new PageList<>(iPage.getTotal(),iPage.getRecords());
    }


    /**
     * 重写save，向商品表和商品的扩展表中添加数据
     * @param entity
     * @return
     */
    @Transactional
    @Override
    public boolean save(Product entity) {
        //插入商品后马上返回商品的主键,mybatis中 useGeneratedKeys=true
        //mybatisplus已经帮我们实现了这个功能，直接用
        baseMapper.insert(entity);//商品表

        //商品扩展表
        ProductExt productExt = entity.getProductExt();
        productExt.setProductId(entity.getId());
        productExtMapper.insert(productExt);

        return true;
    }
}
